<template>
	<view class="user-index">
		<!-- 导航栏 -->
		<tui-navigation-bar :isOpacity="false" @init="initNavigation" backgroundColor="#f5f5f5">
			<view class="location" :style="{ marginTop: top + 'px' }" @click="addressSelect">
				<tui-icon name="gps" :size="22" unit="rpx" color="#000"></tui-icon>
				<tui-text :text="addressName" size="24" fontWeight="600" padding="0 5rpx"></tui-text>
				<view class="angle"></view>
			</view>
		</tui-navigation-bar>

		<!-- 搜索框 -->
		<view class="serach" :style="{ paddingTop: marginTop + 5 + 'px'}">
			<view style="width: 90%;">
				<tui-input @input="input" @confirm="search" @clear="clearInput" padding="16rpx 32rpx" backgroundColor="#fff"
					color="#8A9399" size="28" :borderBottom="false" placeholder="请输入关键词搜索" :radius="40">
					<template v-slot:left>
						<view class="icon">
							<tui-icon name="search" :size="22" color="#8A9399"></tui-icon><strong></strong>
						</view>
					</template>
				</tui-input>
			</view>
			<!-- <view class="tui-notice-box" @click="toMyNews">
				<image src="../../static/user/icon_message@2x.png"></image>
				<tui-badge type="danger" absolute :scaleRatio="0.6" top="-23rpx" right="-20rpx">0</tui-badge>
			</view> -->
		</view>

		<view class="index-con" :style="{ paddingTop: marginTop + 55 + 'px'}">
			<!-- 轮播图 -->
			<view class="tui-banner-swiper">
				<swiper class="tui-banner__height" @change="bannerChange" circular :indicator-dots="false" :interval="4000"
					:duration="150">
					<block v-for="(item,index) in slideList" :key="index">
						<swiper-item>
							<view class="tui-swiper-item tui-banner__height">
								<image :src="ossUrl + (item.imgUrl||'')" mode="aspectFill"></image>
							</view>
						</swiper-item>
					</block>
				</swiper>
				<tui-swiper-dot radius="50%" backgroundColor="#bfbfbf54" activeBgColor="#fff" :count="slideCount"
					:current="slideCurrent"></tui-swiper-dot>
			</view>
			<!-- 推荐商家 -->
			<tui-list-view color="#777">
				<tui-list-cell arrow arrowRight="0" padding="26rpx 0rpx" backgroundColor="#f5f5f5" lineColor="#f5f5f5">
					<view class="thorui-flex__between">
						<tui-text block text="推荐商家" size="36" fontWeight="600" padding="0rpx"></tui-text>
						<tui-text text="更多" size="22" color="#999" padding="0 24rpx 0" @click="moreShop()"></tui-text>
					</view>
				</tui-list-cell>
			</tui-list-view>
			<!-- 商家类型 -->
			<tutor-store-short :ossUrl="ossUrl" :tabs="tabs" @change="changeTabs"></tutor-store-short>
			<!--商家列表-->
			<view :style="merchantList.length ? 'margin-top: 40rpx;' :''">
				<tui-waterfall :listData="merchantList">
					<template v-slot:left="{ list }">
						<MerchantItem :ossUrl="ossUrl" @clickDetail="toShopDetails" v-for="(entity,index) in list" :key="index"
							:entity="entity">
						</MerchantItem>
					</template>
					<template v-slot:right="{ list }">
						<MerchantItem :ossUrl="ossUrl" @clickDetail="toShopDetails" v-for="(entity,index) in list" :key="index"
							:entity="entity">
						</MerchantItem>
					</template>
				</tui-waterfall>
			</view>
			<tutor-tab-1 :list="['最新动态','热门动态']" @clickSwtichTab="clickSwtichTab" :atciveIndex="atciveIndex" padding="0">
				<view class="tab-r" @tap="locationDymic">
					<tui-text text="更多" color="#666666" :size="24"></tui-text>
					<tui-icon name="arrowright" :size="24" margin="0 0 0 -10rpx"></tui-icon>
				</view>
			</tutor-tab-1>
			<!--动态列表-->
			<z-paging ref="paging" use-page-scroll :auto-clean-list-when-reload="false"
				:auto-scroll-to-top-when-reload="false" :default-page-size="pageSize" v-model="dynamicList"
				@query="getDynamicListData">
				<template v-if="dynamicList.length">
					<tui-waterfall :listData="dynamicList">
						<template v-slot:left="{ list }">
							<DynamicItem :ossUrl="ossUrl" :dataList="list" @clickDetail="toDynamicDetail"></DynamicItem>
						</template>
						<template v-slot:right="{ list }">
							<DynamicItem :ossUrl="ossUrl" :dataList="list" @clickDetail="toDynamicDetail"></DynamicItem>
						</template>
					</tui-waterfall>
				</template>
			</z-paging>
		</view>
		<tui-tabbar @clickTabbar="clickTabbar"></tui-tabbar>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import MerchantItem from './compontents/merchantItem.vue'
	import DynamicItem from './compontents/dynamicItem.vue'
	import {
		getSlideshow,
		getMerchantList,
		getCategoryList,
		getDynamicList
	} from "@/http/api/index/index.js"
	import Cache from '@/utils/cache'
	// 使用页面滚动时引入此mixin，用于监听和处理onPullDownRefresh等页面生命周期方法(如果全局引入了，就不要这一步，全局引入示例见main.js)
	import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin'
	export default {
		// 注意这一步不要漏掉，必须注册mixins(如果全局引入了，就不要这一步，全局引入示例见main.js)
		mixins: [ZPMixin],
		components: {
			MerchantItem,
			DynamicItem
		},
		data() {
			return {
				ossUrl: getApp().globalData.ossurl, //图片前缀
				// 导航栏
				top: 0, //标题图标距离顶部距离
				marginTop: 0, // 页面内容距离顶部的距离

				// 定位
				addressName: '未获取',
				latitude: '39.54', //经度
				longitude: '116.25', //维度
				addressInfo: {
					latitude: '', // 纬度
					longitude: '', // 经度
					name: '', // 名称
					province: '', // 省份
					city: '', // 市区
					district: '', // 区域
					businessAreaName: '', // 商圈
				},
				// 轮播图
				slideList: [],
				slideCurrent: 0,
				slideCount: 0,

				// 分类数据列表
				selCategoryId: '',
				tabs: [],

				// 商家列表
				merchantList: [],
				merchantName: '',

				// 动态别表
				dynamicList: [], // v-model绑定的这个变量不要在分页请求结束中自己赋值！！！
				atciveIndex: 0,
				pageSize: 6
			}
		},
		computed: {
			many() {
				const {
					longitude,
					latitude,
					selCategoryId
				} = this
				return {
					longitude,
					latitude,
					selCategoryId
				}
			}
		},
		watch: {
			many(newValue, oldValue) {
				if (newValue.longitude && newValue.latitude && newValue.selCategoryId) {
					// 推荐商家
					this.getMerchantListData();
				}
			},
			// latitude: {
			// 	handler(val,newVal) {
			// 		console.log(val,newVal)
			// 		if (newVal) {
			// 			this.$utils.getAddress(this.latitude, this.longitude,
			// 				'661f987dcae58c7cb089e589ad3c7b18', (obj) => {
			// 					Cache.set('adressNmae', obj.name);
			// 					Cache.set('city', obj.city);
			// 					this.cityName=obj.city 
			// 					this.addressName = obj.name; 
			// 				});
			// 		}else{
			// 			this.$utils.getAddress(this.latitude, this.longitude,
			// 				'661f987dcae58c7cb089e589ad3c7b18', (obj) => {
			// 					Cache.set('adressNmae', obj.name);
			// 					Cache.set('city', obj.city);
			// 					this.cityName=obj.city 
			// 					this.addressName = obj.name; 
			// 				});
			// 		}
			// 	},
			// 	immediate: true
			// }
		},
		onLoad() {
			this.changeTabItem('index')
			this.changeTabBar({
				index: 1,
				pagePath: '/pages/index/index'
			});
			this.cityName = Cache.get('city');
			this.addressName = Cache.get('adressNmae');
			this.latitude = Cache.get('latitude');
			this.longitude = Cache.get('longitude');
			// 分类数据 
			getCategoryList().then(res => {
				if (res.code == 200) {
					const list = res.data || [];
					this.tabs = list.slice(0, 4)
					this.selCategoryId = res?.data[0].id;
					uni.setStorageSync('categoryList', res.data);
				} else {
					this.$utils.toast("首页-分类 " + res.msg);
				}
			})
			// 轮播数据
			this.getSwiperData();
			this.getLocation()
			uni.$on('adressInfo', (e) => {
				this.load(e)
			})
		},
		beforeCreate() {
			console.log('index')
			// #ifdef APP-PLUS
			uni.hideTabBar();
			// #endif
		},
		onUnload() {
			uni.$off('adressInfo')
		},
		methods: {
			// 搜索框相关事件
			search(e) {
				this.merchantName = e.detail.value;
				this.getMerchantListData();
			},
			clearInput() {
				this.merchantName = '';
				this.getMerchantListData();
			},
			input(e) {
				this.merchantName = e;
				this.getMerchantListData();
			},
			load(e) {
				this.latitude = e.latitude
				this.longitude = e.longitude
				this.addressInfo.name = e.name
				this.addressName = e.address
				this.addressInfo = e
				Cache.set('longitude', e.longitude)
				Cache.set('latitude', e.latitude)
				Cache.set('city', !Array.isArray(e.poi.city) ? e.poi.city : e.poi.province)
				Cache.set('adressNmae', e.address)
			},
			...mapMutations(['changeTabItem', 'changeTabBar']),
			clickTabbar(detils) {
				this.changeTabBar(detils)
				console.log(detils, '点击')
			},
			// 导航栏
			initNavigation(e) {
				this.top = e.top;
				this.marginTop = e.height;
			},
			locationDymic() {
				this.changeTabItem('index')
				this.changeTabBar({
					index: 3,
					pagePath: '/pages/find/find'
				});
			},
			// 获取当前定位的经纬度
			getLocation() {
				let self = this
				getApp().globalData.initJssdk((jweixin) => {
					jweixin.getLocation({
						type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
						success: res => {
							self.latitude = res.latitude;
							self.longitude = res.longitude;

						},
						fail: function(err) {
							// 处理获取位置失败的情况 
							console.error('获取位置失败', err);
							self.$utils.toast('获取位置失败，请检查定位权限' + err);
						}
					});
				})
			},
			// 跳转到地址选择界面
			addressSelect() {
				let info = JSON.stringify({
					latitude: this.latitude,
					address: this.addressName,
					longitude: this.longitude
				});
				uni.navigateTo({
					url: '/pages/index/modules/addressSelect/addressSelect?info=' + info
				})
			},
			// 动态详情
			toDynamicDetail(e) {
				let dynamicId = e.dynamic.id;
				const token = Cache.get('access_token')
				if (!token) {
					uni.showModal({
						title: '暂未登录',
						content: '请登录',
						confirmText: '前往登录',
						success: function(res) {
							if (res.confirm) {
								uni.reLaunch({
									url: `/pages/mine/modules/userLogin/userLogin`
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				} else {
					uni.navigateTo({
						url: '/pages/find/modules/recommendDetails/recommendDetails?dynamicId=' + dynamicId
					})
				}
			},
			// 轮播图
			bannerChange: function(e) {
				this.slideCurrent = e.detail.current;
			},
			// 类型切换tab
			changeTabs(e) {
				this.selCategoryId = e.categoryId;
				this.$refs.paging.reload();
			},
			// 动态切换
			clickSwtichTab(e) {
				this.atciveIndex = e.index
				this.$refs.paging.reload();
			},
			//进入商家详情
			toShopDetails(e) {
				const token = Cache.get('access_token')
				if (!token) {
					uni.showModal({
						title: '暂未登录',
						content: '请登录',
						confirmText: '前往登录',
						success: function(res) {
							if (res.confirm) {
								uni.reLaunch({
									url: `/pages/mine/modules/userLogin/userLogin`
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				} else {
					uni.navigateTo({
						url: '/pages/index/modules/shopDetails/shopDetails?id=' + e.id
					})
				}
			},
			// 更多商家
			moreShop: function() {
				uni.navigateTo({
					url: '/pages/index/modules/moreShop/moreShop'
				})
			},
			// 我的消息
			toMyNews: function() {
				const token = Cache.get('access_token')
				if (token) {
					uni.navigateTo({
						url: '/pages/mine/modules/myNews/myNews'
					})
				} else {
					uni.showModal({
						title: '暂未登录',
						content: '请登录',
						confirmText: '前往登录',
						success: function(res) {
							if (res.confirm) {
								uni.reLaunch({
									url: `/pages/mine/modules/userLogin/userLogin`
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				}
			},
			// 轮播数据
			getSwiperData() {
				// 启动页 1，banner 2首页，3，教练，4动态
				getSlideshow({
					type: 2
				}).then(res => {
					if (res.code == 200) {
						this.slideList = res.data;
						this.slideCount = res.data.length;
					} else {
						this.$utils.toast("首页-轮播 " + res.msg)
					}
				}).catch(error => {
					this.$utils.toast("首页-轮播 " + error);
				})
			},
			// 推荐商家数据
			getMerchantListData() {
				let params = {
					pageNum: 1,
					pageSize: 4,
					merchantName: this.merchantName,
					categoryId: this.selCategoryId,
					longitude: this.longitude,
					latitude: this.latitude
				}
				getMerchantList(params).then(res => {
					if (res.code == 200) {
						this.merchantList = res.rows
					} else {
						this.$utils.toast("首页-推荐商家 " + res.msg)
					}
				}).catch(error => {
					this.$utils.toast("首页-推荐商家 " + error);
				})
			},
			// 动态列表分页
			getDynamicListData(pageNo, pageSize) {
				// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				// 模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageNum: pageNo,
					pageSize: pageSize,
					queryType: this.atciveIndex ? "1" : "2" // 1 热门，2 最新
				}
				getDynamicList(params).then(res => {
					if (res.code == 200) {
						// 将请求的结果数组传递给z-paging 
						this.$refs.paging.complete(res.rows);
					} else {
						this.$utils.toast("首页-动态 " + res.msg)
					}
				}).catch(res => {
					// 如果请求失败写this.$refs.paging.complete(false);
					// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
					// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
					this.$refs.paging.complete(false);
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	.user-index {
		width: 100%;
		background-color: #f5f5f5 !important;
		padding-bottom: 200rpx;

		/* 导航栏 */
		.location {
			width: 94%;
			position: fixed;
			top: 0;
			padding: 0 0 0 3%;
			display: flex;
			align-items: center;
			height: 32px;
			transform: translateZ(0);
			box-sizing: border-box;

			.angle {
				width: 0;
				height: 0;
				border-left: 4px solid transparent;
				border-right: 4px solid transparent;
				border-top: 6px solid #000;
			}
		}

		/** 搜索框 */
		.serach {
			position: fixed;
			z-index: 1;
			background-color: #f5f5f5;
			width: 100%;
			padding-left: 3%;
			padding-right: 6%;
			padding-bottom: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: flex-end;

			.serach-bar {
				width: 100%;
				height: 40px;
			}

			.tui-notice-box {
				position: relative;
				flex-shrink: 0;
				font-size: 44rpx;

				image {
					width: 35rpx;
					height: 45rpx;
				}
			}
		}

		.index-con {
			width: 94%;
			padding-left: 3%;

			/** 轮播图 */
			.tui-banner-swiper {
				position: relative;

				.tui-banner__height {
					height: 360rpx;

					.tui-swiper-item {
						width: 100%;
						color: #FFFFFF;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 34rpx;
						font-weight: 600;

						image {
							width: 100%;
							height: 100%;
							border-radius: 20rpx;
						}
					}
				}
			}

			/* 动态 */
			.tab-r {
				display: flex;
				align-items: center;
			}
		}
	}
</style>